from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
import jwt
from meiduo import settings
class LoginMiddleware(MiddlewareMixin):
    def process_request(self,request):
        white = ['/users/login/','/users/reg/']

        url = request.get_full_path()
        print(request.META)
        if url not in white:
            #业务处理
            if request.META.get('HTTP_AUTHORIZATION'):
                try:
                     #解析token
                    token = request.META.get('HTTP_AUTHORIZATION')
                    s = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
                    #重新生成token
                    newtoken = str(jwt.encode(s,settings.SECRET_KEY,algorithm='HS256'),encoding='utf8')
                    if token == newtoken:
                        return None
                except:
                    return JsonResponse({'code':401})
        else:
            return None